package edu.spec.basic.service.impl;

import edu.spec.basic.dao.iface.ICommandDao;
import edu.spec.basic.dao.iface.IModuleDao;
import edu.spec.basic.model.Command;
import edu.spec.basic.model.Module;
import edu.spec.basic.service.iface.ICommandService;
import edu.spec.basic.service.iface.IModuleService;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.List;

@Service
public class ModuleService implements IModuleService {

    @Inject
    private IModuleDao moduleDao;
	@Inject
	private ICommandDao commandDao;
	@Inject
	private ICommandService commandService;

	@Override
	public void add(Module module) {
		moduleDao.add(module);
	}

	// TODO 性能有待优化
	@Override
	public void delete(int id) {
		List<Integer> ids = moduleDao.listModuleIdByParent(id);
		if(ids!=null && ids.size()>0){
			for (Integer i : ids){
				delete(i);
			}
		}
		// 此时id对应的Module一定是leaf
		deleteLeafModule(id);
	}

	private void deleteLeafModule(Integer id){
		List<Command> cs = commandDao.listCommandByModule(id);
		for(Command c : cs){
			commandService.delete(c.getId());
		}
		moduleDao.delete(id);
	}

	@Override
	public Module load(int id) {
		return moduleDao.load(id);
	}

	@Override
	public void update(Module module) {
		moduleDao.update(module);
	}

	@Override
    public List<Module> listAllModule() {
        return moduleDao.listAllModule();
    }

	@Override
	public List<Module> listModuleByRoles(List<Integer> roleIds) {
		return moduleDao.listModuleByRoles(roleIds);
	}

	@Override
	public List<Module> listModuleByParent(int parentId) {
		return moduleDao.listModuleByParent(parentId);
	}
}
